import csv
import json
import os
import tkinter as tk
from tkinter import filedialog

def csv_to_jsonl(csv_file_path):
    """将 CSV 文件转换为 JSONL 文件"""
    jsonl_file_path = os.path.splitext(csv_file_path)[0] + ".jsonl"

    with open(csv_file_path, mode='r', encoding='utf-8') as csv_file, \
         open(jsonl_file_path, mode='w', encoding='utf-8') as jsonl_file:
        
        csv_reader = csv.DictReader(csv_file)
        
        for row in csv_reader:
            jsonl_file.write(json.dumps(row, ensure_ascii=False) + '\n')

    print(f"转换成功: {jsonl_file_path}")

def select_file():
    """打开文件选择对话框"""
    file_path = filedialog.askopenfilename(filetypes=[("CSV 文件", "*.csv")])
    if file_path:
        csv_to_jsonl(file_path)

# 创建 GUI
root = tk.Tk()
root.title("CSV 转 JSONL 工具")
root.geometry("300x150")

label = tk.Label(root, text="选择 CSV 文件进行转换", padx=10, pady=10)
label.pack()

btn = tk.Button(root, text="选择文件", command=select_file)
btn.pack()

root.mainloop()
